jQuery.noConflict();
var aeRequest;
var loading_done = false;
var local_id_shedulerActivity;
var ShedulerActivityArray = new Array();
var ActivityArray = new Array();
var typeofActivityArray = new Array();
var dayArray = new Array();
var day_chose;
var AdminArray = new Array();
function createResponseXML(textXML) {
    // code for IE
    if (window.ActiveXObject) {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(textXML);
        return xmlDoc;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else {
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(textXML, "text/xml");
        return xmlDoc;
    }
}


function createXmlHttpRequestObject() {
    var ro;
    var browser = navigator.appName;
    // Need to determine IE7 and not do this.
    if (browser == "Microsoft Internet Explorer") {
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else {
        ro = new XMLHttpRequest();
    }
    return ro;
}

function openDivbyUrl(id){
    if(id=='Div_createSA'){
        setVisiableFieldset_tableshowActiv(false);
        //getTypeActivityByAjax();
        if(loading_done){
            setVisiableDiv_createSA(true);
            loading_done = false;
        } 
    }
    if(id =='tableshowActiv'){
        setVisiableDiv_createSA(false);
        getAllShedulerActivityByAjax();
        if(loading_done){
            setVisiableFieldset_tableshowActiv(true);
            loading_done = false;
        }
       
    }
}

function getSessionByAjax(){
    AdminArray.splice(0,AdminArray.length);
    var url='http://localhost:8080/NLPP_SEM4/LoadDataServlet?type=getsession';//getsession login danh cai duong dan vao day
    aeRequest = createXmlHttpRequestObject();
    aeRequest.open("POST", url, true);
    aeRequest.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
    aeRequest.setRequestHeader("Content-length", 0);
    aeRequest.setRequestHeader("Connection", "close");
    aeRequest.onreadystatechange = function() {
        if (aeRequest.readyState == 4) {
            if (aeRequest.status == 200) {
                var response = createResponseXML(aeRequest.responseText);
                var result = response.getElementsByTagName("result")[0].firstChild.nodeValue;	
                if(result == 'error'){
                    window.location.href="";
                }else{
                    var name = response.getElementsByTagName("username")[0].firstChild.nodeValue;
                    var id = response.getElementsByTagName("id")[0].firstChild.nodeValue;
                    var type_user = response.getElementsByTagName("type")[0].firstChild.nodeValue;
                    AdminArray.push(new Array(id,name,type_user));
                    drawAdminName(AdminArray);
                    var type = getUrlVars()["type"];
                    initMenu();
                    openDivbyUrl(type);
                }
            }
        }
    };
    aeRequest.send(null);
}

function getAllShedulerActivityByAjax(){
    ShedulerActivityArray.splice(0,ShedulerActivityArray.length);
    var url='http://localhost:8080/NLPP_SEM4/LoadDataServlet?type=getsession';//getsession login
    aeRequest = createXmlHttpRequestObject();
    aeRequest.open("POST", url, true);
    aeRequest.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
    aeRequest.setRequestHeader("Content-length", 0);
    aeRequest.setRequestHeader("Connection", "close");
    aeRequest.onreadystatechange = function() {
        if (aeRequest.readyState == 4) {
            if (aeRequest.status == 200) {
                var response = createResponseXML(aeRequest.responseText);
                var result = response.getElementsByTagName("result")[0].firstChild.nodeValue;	
                if(result == 'error'){
                    alert("please try again server is taking too long");
                    loading_done = true;
                }else{
                    var sa = response.getElementsByTagName("SA");
                    for(var i = 0 ; i < sa.length;i++){
                        var id = sa[i].getElementsByTagName("id")[0].firstChild.nodeValue;
                        var title = sa[i].getElementsByTagName("title")[0].firstChild.nodeValue;
                        var description = sa[i].getElementsByTagName("description")[0].firstChild.nodeValue;
                        var location = sa[i].getElementsByTagName("location")[0].firstChild.nodeValue;
                        var startdate = sa[i].getElementsByTagName("startdate")[0].firstChild.nodeValue;
                        var enddate = sa[i].getElementsByTagName("enddate")[0].firstChild.nodeValue;
                        var status = sa[i].getElementsByTagName("status")[0].firstChild.nodeValue;
                        ShedulerActivityArray.push(new Array(status,id,title,startdate,enddate,description,location))
                    }
                    loading_done = true;
                }
            }
        }
    };
    aeRequest.send(null);
    
}
function saveShedulerActivity(title,description,location,startdate,enddate){ 
    dayArray.splice(0,dayArray.length);
    var url='http://localhost:8080/NLPP_SEM4/ScheduleActivityServlet?action=add&scheduletitle='+ title + "&schedulestartdate=" + startdate;
    url += "&scheduleenddate=" + enddate + "&scheduleaddress=" + location;
    url += "&scheduledescription=" + description;
    //alert(url);//chua qua port nay??
    //danh duong dan url ma khi tao bat dau create sheduer activity thanh cong thi tra ve 1 mang day voi cai id cua shedulerActitivity day nha
    aeRequest = createXmlHttpRequestObject();
    aeRequest.open("POST", url, true);
    aeRequest.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
    aeRequest.setRequestHeader("Content-length", 0);
    aeRequest.setRequestHeader("Connection", "close");
    aeRequest.onreadystatechange = function() {
        if (aeRequest.readyState == 4) {
            if (aeRequest.status == 200) {
                var response = createResponseXML(aeRequest.responseText);
                var result = response.getElementsByTagName("result")[0].firstChild.nodeValue;
                //var result = response.getElementsByTagName("message")[0].firstChild.nodeValue;
                if(result == 'error'){
                    alert("please try again server is taking too long");                
                }else{
                    //cho nay nhu la ko khop url? URL chi tra ve ID thoi
                    var id = response.getElementsByTagName("scheduleid")[0].firstChild.nodeValue;
                    //cai list day la ben servlet load data
                    var allday = response.getElementsByTagName("allday")[0].firstChild.nodeValue;
                    var days = allday.split(",");
                    local_id_shedulerActivity = id;
                    for(var i = 0 ; i < days.length;i++){
                        dayArray.push(days[i]);
                    }
                    if(setVisiableDiv_createSA_alert_success('please wait when we create data')){
                        drawHeader_Div_Activity(dayArray,title);
                        setVisiableDiv_createSA(false);
                        setVisiableDiv_showAll_Activity(false);
                        setVisiableDiv_Activity(true);
                    }
                   
                //alert("add success");
                }
            }
        }
    };
    aeRequest.send(null);
}
//saveActivity(title, typeOfActivity, address, time_start, time_end, max_people, Fee, send_to, description);
function saveActivity(title, typeOfActivity, address, time_start, time_end, max_people, Fee, send_to, description){
    var duration_time = time_start +' to '+ time_end;
    
    var url='http://localhost:8080/NLPP_SEM4/ActivityServlet?action=add';
    url += "&scheduleid=" + local_id_shedulerActivity;
    url+= "&activitytitle="+title;
    url+="&activityemailorganizer="+send_to;
    url += "&activitylocation=" + address;
    url += "&activitydate=" + day_chose;
    url += "&activitytimeduration="+duration_time ;
    url += "&activitylimittedpeople=" + max_people;
    url += "&activityfee=" + Fee;
    url += "&activitydescription="+description;
    url+= "&typeofactivityid="+typeOfActivity;
    aeRequest = createXmlHttpRequestObject();
    aeRequest.open("POST", url, true);
    aeRequest.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
    aeRequest.setRequestHeader("Content-length", 0);
    aeRequest.setRequestHeader("Connection", "close");
    aeRequest.onreadystatechange = function() {
        if (aeRequest.readyState == 4) {
            if (aeRequest.status == 200) {
                //alert(aeRequest.responseText);
                var response = createResponseXML(aeRequest.responseText);
                var result = response.getElementsByTagName("result")[0].firstChild.nodeValue;	
                if(result != 'success'){
                    setVisiableDiv_Activity_alert_warning("please try again server is taking too long");                
                }else{
                    setVisiableDiv_Activity_alert_success("Add activity success");
                    showActivitybyDay(local_id_shedulerActivity, day_chose);
                }
            }
        }
    };
    aeRequest.send(null);
}
function showActivitybyDay(idShedulerActivity,day){
    ActivityArray.splice(0,ActivityArray.length);
    day_chose = day;
    var url='http://localhost:8080/NLPP_SEM4/LoadDataServlet?type=getactivitiesbydayandscheduleid';//load tat ca cac activity trong ngay xac dinh
    url = url + '&scheduleid=' + idShedulerActivity;
    url +='&activitydate=' + day_chose;
    //alert(url);
    aeRequest = createXmlHttpRequestObject();
    aeRequest.open("POST", url, true);
    aeRequest.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
    aeRequest.setRequestHeader("Content-length", 0);
    aeRequest.setRequestHeader("Connection", "close");
    aeRequest.onreadystatechange = function() {
        if (aeRequest.readyState == 4) {
            if (aeRequest.status == 200) {
                // alert(aeRequest.responseText);
                var response = createResponseXML(aeRequest.responseText);
                var result = response.getElementsByTagName("result")[0].firstChild.nodeValue;
                //alert(result);
                if(result == 'error'){
                    //alert("please try again server is taking too long");
                    setVisiableDiv_Activity_alert_warning("Some error from server please try again");
                }else if(result == 'null'){
                    // alert('non con cai co');
                    drawTableshowActivity(ActivityArray,day_chose);
                    setVisiableFieldset_tableshowActiv(true);
                    setVisiableFieldset_configActive(true);
                }
                else{
                    // alert("going");
                    var events = response.getElementsByTagName("activity");
                    //alert(events);
                    for(var i = 0;i < events.length;i++){                       
                        var id = events[i].getElementsByTagName("activityid")[0].firstChild.nodeValue;//0
                        var title =  events[i].getElementsByTagName("activitytitle")[0].firstChild.nodeValue;//1
                        //var talkaboutid = events.getElementsByTagName("typeofactivityid")[0].firstChild.nodeValue;
                        var talkabout = events[i].getElementsByTagName("typeofactivityname")[0].firstChild.nodeValue;//2
                        var fee = events[i].getElementsByTagName("activityfee")[0].firstChild.nodeValue;//3
                        var address = events[i].getElementsByTagName("activitylocation")[0].firstChild.nodeValue;//4
                        var start_time = events[i].getElementsByTagName("activitytimeduration")[0].firstChild.nodeValue;//5
                        //var end_time = events[i].getElementsByTagName("end_time")[0].firstChild.nodeValue;
                        var max_people = events[i].getElementsByTagName("activitylimittedpeople")[0].firstChild.nodeValue;//6
                        var description = events[i].getElementsByTagName("activitydescription")[0].firstChild.nodeValue;//7
                        var sendto = events[i].getElementsByTagName("activityemailorganizer")[0].firstChild.nodeValue;//8
                        ActivityArray.push(new Array(id,title,talkabout,fee,start_time,max_people,address,description,sendto));
                        
                    }
                    drawTableshowActivity(ActivityArray,day_chose);
                    setVisiableFieldset_tableshowActiv(true);
                }
            }
        }
    };
    aeRequest.send(null);
}
function getTypeActivityByAjax(){
    var url='http://localhost:8080/NLPP_SEM4/LoadDataServlet?type=gettypeofactivity';//getsession login
    aeRequest = createXmlHttpRequestObject();
    aeRequest.open("POST", url, true);
    aeRequest.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
    aeRequest.setRequestHeader("Content-length", 0);
    aeRequest.setRequestHeader("Connection", "close");
    aeRequest.onreadystatechange = function() {
        if (aeRequest.readyState == 4) {
            if (aeRequest.status == 200) {
                var response = createResponseXML(aeRequest.responseText);
                var result = response.getElementsByTagName("result")[0].firstChild.nodeValue;
                if(result == 'error'){
                    setVisiableDiv_createSA_alert_warning("Some error from server please try again");
                }else{
                    var types = response.getElementsByTagName("typeofactivity");
                    if(types.length > 0){
                        typeofActivityArray.splice(0,typeofActivityArray.length);
                        for(var i = 0 ; i < types.length;i++){
                            var id = types[i].getElementsByTagName("typeofactivityid")[0].firstChild.nodeValue;
                            var name = types[i].getElementsByTagName("typeofactivityname")[0].firstChild.nodeValue;
                            typeofActivityArray.push(new Array(id,name));
                            drawTypeOfActivitySelect(typeofActivityArray);
                        }
                    }
                    loading_done = true;
                }
            }
        }
    };
    aeRequest.send(null);
}

function openEditActivityForm(id){
 
    var location = jQuery("#"+id).offset();
    var left = parseInt(location.left);
    var top = parseInt(location.top);
    jQuery("#EditActivityContainer").css("left",left);
    jQuery("#EditActivityContainer").css("top",top);
    for(var i = 0 ; i < ActivityArray.length;i++){
        if(ActivityArray[i][0] == id){
            //ActivityArray.push(new Array(id,title,talkabout,fee,start_time,max_people,address));
            jQuery("#idhidden").val(ActivityArray[i][0]);
            jQuery("#titleofActivi_edit").val(ActivityArray[i][1]);
            jQuery("#typeOfActivity_edit").val(ActivityArray[i][2]);//ko xit dau cu cho gia tri la no se hien ra
            jQuery("#FeeofActivi_edit").val(ActivityArray[i][3]);
            var timeStart = ActivityArray[i][4].split("to")[0];
            var timeEnd = ActivityArray[i][4].split("to")[1];          
            jQuery("#timeStartofActivi_edit").val(timeStart);
            jQuery("#timeEndofActivi_edit").val(timeEnd);
            jQuery("#limitedAccessofActivi_edit").val(ActivityArray[i][5]);
            jQuery("#addressOfActivi_edit").val(ActivityArray[i][6]);
            jQuery("#descripofActivi_edit").val(ActivityArray[i][7]);
            jQuery("#sendToofActivi_edit").val(ActivityArray[i][8]);
        }
    }
    if(isShow_div_editActivity){
        setVisiable_div_EditActivity(false);
    }else{
        setVisiable_div_EditActivity(true);
    }
    
}

function updateActivity(id,title, typeOfActivity, address, time_start, time_end, max_people, Fee, send_to, description){
    var duration_time = time_start +' to '+ time_end;
    var url='http://localhost:8080/NLPP_SEM4/ActivityServlet?action=update';
    url += "&scheduleid=" + local_id_shedulerActivity;
    url+="$activityid="+id;
    url+= "&activitytitle="+title;
    url+="&activityemailorganizer"+ send_to;
    url += "&activitylocation=" + address;
    url += "&activitydate=" + day_chose;
    url += "&activitytimeduration="+duration_time ;
    url += "&activitylimittedpeople=" + max_people;
    url += "&activityfee=" + Fee;
    url += "&activitydescription"+description;
    url+= "&typeofactivityid"+typeOfActivity;
    aeRequest = createXmlHttpRequestObject();
    aeRequest.open("POST", url, true);
    aeRequest.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
    aeRequest.setRequestHeader("Content-length", 0);
    aeRequest.setRequestHeader("Connection", "close");
    aeRequest.onreadystatechange = function() {
        if (aeRequest.readyState == 4) {
            if (aeRequest.status == 200) {
                //alert(aeRequest.responseText);
                var response = createResponseXML(aeRequest.responseText);
                var result = response.getElementsByTagName("result")[0].firstChild.nodeValue;	
                if(result != 'success'){
                    setVisiableDiv_Activity_alert_warning("please try again server is taking too long");                
                }else{
                    setVisiableDiv_Activity_alert_success("Add activity success");
                    showActivitybyDay(local_id_shedulerActivity, day_chose);
                    setVisiable_div_EditActivity(false);
                }
            }
        }
    };
    aeRequest.send(null);
}

jQuery(document).ready(function() {
    //getSessionByAjax();
    getTypeActivityByAjax();
    jQuery("#SA_SUBMIT").click(function(){
        var title = jQuery("#txtTitleSA").val();
        var description = jQuery("#txtDescripSA").val();
        var location = jQuery("#txtLocaSA").val();
        var startdate = jQuery("#SA_startdate").val();
        var enddate = jQuery("#SA_enddate").val();
        if(validate_Div_createSA()){
            //alert('going');//chay di xem nao
            saveShedulerActivity(title, description, location, startdate, enddate);
        }
    });
    jQuery("#addActiv").click(function(){
        var day = jQuery("#select_allday").val();
        showActivitybyDay(local_id_shedulerActivity, day);
    });
    jQuery("#closeActiv").click(function(){
        setVisiableFieldset_configActive(false);
        setVisiableFieldset_tableshowActiv(false);
    });
    jQuery("#BackToShedulerActivity").click(function(){
        setVisiableDiv_createSA(true);
        setVisiableDiv_showAll_Activity(false);
        setVisiableDiv_Activity(false);
    });
    jQuery("#SA_RESET").click(function(){
        cleardata_div_createSA();
    });
    jQuery("#save_activity").click(function(){
        var title = jQuery("#titleofActivi").val();
        var typeOfActivity = jQuery("#typeOfActivity").val();
        var address = jQuery("#addressOfActivi").val();
        var time_start = jQuery("#timeStartofActivi").val();
        var time_end = jQuery("#timeEndofActivi").val();
        var max_people = jQuery("#limitedAccessofActivi").val();
        var send_to = jQuery("#sendToofActivi").val();
        var Fee = jQuery("#FeeofActivi").val();
        var description = jQuery("#descripofActivi").val();
        //alert(time_start + time_end + address+ send_to + "--");
        if(validate_field_configActive()){
            saveActivity(title, typeOfActivity, address, time_start, time_end, max_people, Fee, send_to, description);
        }
    });
    jQuery("#edit_activity").click(function(){
        var id = jQuery("#idhidden").val();
        var title = jQuery("#titleofActivi_edit").val();
        var typeOfActivity = jQuery("#typeOfActivity_edit").val();
        var address = jQuery("#addressOfActivi_edit").val();
        var time_start = jQuery("#timeStartofActivi_edit").val();
        var time_end = jQuery("#timeEndofActivi_edit").val();
        var max_people = jQuery("#limitedAccessofActivi_edit").val();
        var send_to = jQuery("#sendToofActivi_edit").val();
        var Fee = jQuery("#FeeofActivi_edit").val();
        var description = jQuery("#descripofActivi_edit").val();
        if(validate_field_EditActive()){
            updateActivity(id, title, typeOfActivity, address, time_start, time_end, max_people, Fee, send_to, description);
        }
    });
    
   
});

